import config from '../../config/config'
import { PhotoService } from '../../services/photo_service'
import uploadFile from '../../utils/uploadImage'
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import { OrderService } from '../../services/order_service'

var imageList = {}
var colorMap = {
	blue: '#568BDB',
	dark_blue: '#30537E',
	gradient: 'linear-gradient(#5388DE, #AAC5EF)',
	grey: 'linear-gradient(#66697E, #989AA6)',
	red: '#EC3816',
	tint: '#78B1F2',
	white: '#ffffff',
	dark_red: '#8A1E1E',
}

var originalImagePath
var productId
var releatedId
var originalImageUrl
var category

var photoId
var pic_id = ''
var width = 0
var height = 0

const app = getApp()

Page({
	data: {
		tabs: [],
		activeTab: 0,
		image: '',
		colorList: [],
		selectedColor: 'blue',
		activeDialog: 0,
		whitening: 0,
		selectedClothType: 0,
		clothes: {
			boy: [{
					key: 'boy_01',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/01.png',
					title: '男装1',
				},
				{
					key: 'boy_02',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/02.png',
					title: '男装2',
				},
				{
					key: 'boy_03',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/03.png',
					title: '男装3',
				},
				{
					key: 'boy_04',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/04.png',
					title: '男装4',
				},
				{
					key: 'boy_05',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/05.png',
					title: '男装5',
				},
				{
					key: 'boy_06',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/06.png',
					title: '男装5',
				},
				{
					key: 'boy_07',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/07.png',
					title: '男装7',
				},
				{
					key: 'boy_08',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/08.png',
					title: '男装8',
				},
				{
					key: 'boy_09',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/09.png',
					title: '男装9',
				},
				{
					key: 'boy_10',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/10.png',
					title: '男装10',
				},
				{
					key: 'boy_11',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/11.png',
					title: '男装11',
				},
				{
					key: 'boy_12',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/12.png',
					title: '男装13',
				},
				{
					key: 'boy_13',
					value: 'https://static.fishto.cn/images/icon-clothes/boy/13.png',
					title: '男装12',
				},
			],
			girl: [{
					key: 'girl_01',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/01.png',
					title: '女装1',
				},
				{
					key: 'girl_02',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/02.png',
					title: '女装2',
				},
				{
					key: 'girl_03',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/03.png',
					title: '女装3',
				},
				{
					key: 'girl_04',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/04.png',
					title: '女装4',
				},
				{
					key: 'girl_05',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/05.png',
					title: '女装5',
				},
				{
					key: 'girl_06',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/06.png',
					title: '女装6',
				},
				{
					key: 'girl_07',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/07.png',
					title: '女装7',
				},
				{
					key: 'girl_08',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/08.png',
					title: '女装8',
				},
				{
					key: 'girl_09',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/09.png',
					title: '女装9',
				},
				{
					key: 'girl_10',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/10.png',
					title: '女装10',
				},
				{
					key: 'girl_11',
					value: 'https://static.fishto.cn/images/icon-clothes/girl/11.png',
					title: '女装11',
				},
			],
			child: [{
					key: 'child_01',
					value: 'https://static.fishto.cn/images/icon-clothes/child/01.png',
					title: '童装1',
				},
				{
					key: 'child_02',
					value: 'https://static.fishto.cn/images/icon-clothes/child/02.png',
					title: '童装2',
				},
				{
					key: 'child_03',
					value: 'https://static.fishto.cn/images/icon-clothes/child/03.png',
					title: '童装3',
				},
				{
					key: 'child_04',
					value: 'https://static.fishto.cn/images/icon-clothes/child/04.png',
					title: '童装4',
				},
				{
					key: 'child_05',
					value: 'https://static.fishto.cn/images/icon-clothes/child/05.png',
					title: '童装5',
				},
				{
					key: 'child_06',
					value: 'https://static.fishto.cn/images/icon-clothes/child/06.png',
					title: '童装6',
				},
				{
					key: 'child_07',
					value: 'https://static.fishto.cn/images/icon-clothes/child/07.png',
					title: '童装7',
				},
				{
					key: 'child_08',
					value: 'https://static.fishto.cn/images/icon-clothes/child/08.png',
					title: '童装8',
				},
				{
					key: 'child_09',
					value: 'https://static.fishto.cn/images/icon-clothes/child/09.png',
					title: '童装9',
				},
			],
		},
		selectedCloth: 'none',
		free: 0,
		orderId: '',
	},

	onLoad(options) {
		const tabs = [{
				title: '单张照预览',
			},
			{
				title: '排版照预览',
			},
		]
		if (options != null) {
			imageList = JSON.parse(options.list)
			console.log('==imageList', imageList)
			//imageList = {white: "https://api.zheyings.cn/pics/2024110822/672e2567c3…6b0cde3609a/685ff589c0d76cae10dd5630d355a2fa.jpeg"}
			pic_id = options.pic_id
			originalImagePath = options.originalImagePath
			originalImageUrl = options.originalImageUrl
			productId = options.productId
			releatedId = options.releatedId
			photoId = options.photoId
			width = options.width
			height = options.height
			category = options.category
		}
		this.setData({
			tabs,
			image: Object.values(imageList)[0],
			selectedColor: Object.keys(imageList)[0],
			free: options.free,
			orderId: options.orderId,
			colorList: Object.keys(imageList).map((item) => {
				return {
					key: item,
					value: colorMap[item],
				}
			}),
		})
	},

	onTabClick(e) {
		const index = e.detail.index
		this.setData({
			activeTab: index,
		})
	},

	onChange(e) {
		const index = e.detail.index
		this.setData({
			activeTab: index,
		})
	},

	// 美颜
	onSliderValueChange(e) {
		wx.showLoading({
			title: '处理中',
		})
		this.setData({
			whitening: e.detail.value,
		})
		let fs = wx.getFileSystemManager()
		let image = fs.readFileSync(originalImagePath, 'base64', 0)
		if (this.data.free == 1) {
			wx.request({
				url: 'https://api.zheyings.cn/idcardv3/diy',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded', // 默认值
				},
				data: {
					key: config.apiKey,
					item_id: releatedId,
					image,
					beauty: 1,
					width_px: width,
					height_px: height,
					whitening: e.detail.value,
				},
				success: (res) => {
					wx.hideLoading()
					imageList = res.data.data.list
					pic_id = res.data.data.pic_id
					this.setData({
						image: imageList[this.data.selectedColor],
						selectedCloth: 'none',
					})
				},
			})
		} else {
			wx.request({
				url: 'https://api.zheyings.cn/idcardv5/make',
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded', // 默认值
				},
				data: {
					key: config.apiKey,
					item_id: releatedId,
					image,
					beauty: 1,
					whitening: e.detail.value,
				},
				success: (res) => {
					wx.hideLoading()
					imageList = res.data.data.list
					pic_id = res.data.data.pic_id
					this.setData({
						image: imageList[this.data.selectedColor],
						selectedCloth: 'none',
					})
				},
			})
		}
	},

	changeColor(e) {
		console.log(e)
		const color = e.currentTarget.dataset.color
		this.setData({
			image: imageList[color],
			selectedColor: color,
			selectedCloth: 'none',
		})
	},

	changeDialog(e) {
		const index = e.currentTarget.dataset.index
		if (index == this.data.activeDialog) {
			this.setData({
				activeDialog: -1,
			})
		} else {
			this.setData({
				activeDialog: index,
			})
		}
	},

	// 切换服装类型
	changeClothType(e) {
		let type = e.currentTarget.dataset.type
		this.setData({
			selectedClothType: type,
		})
	},

	// 换装
	changeCloth(e) {
		let key = e.currentTarget.dataset.key

		if (key == 'none') {
			this.setData({
				selectedCloth: key,
				image: imageList[this.data.selectedColor],
			})
			return
		}

		wx.showLoading({
			title: '处理中',
			mask: true,
		})
		wx.request({
			url: 'https://api.zheyings.cn/idcardv5/clothes',
			method: 'POST',
			header: {
				'content-type': 'application/x-www-form-urlencoded', // 默认值
			},
			data: {
				key: config.apiKey,
				pic_id: pic_id,
				color: this.data.selectedColor,
				clothes: key,
			},
			success: (res) => {
				if (res.data.code == 0) {
					this.setData({
						image: res.data.data.pic,
						selectedCloth: key,
					})
					wx.hideLoading()
				} else {
					wx.hideLoading()
					wx.showToast({
						icon: 'error',
						title: res.data.msg,
					})
				}
			},
		})
	},

	onChangeClothClose() {
		this.setData({
			activeDialog: -1,
		})
	},

	nextStep() {
		if (this.data.free == 1) {
			wx.getImageInfo({
				src: this.data.image,
				success: (res) => {
					wx.saveImageToPhotosAlbum({
						filePath: res.path,
						success: (res) => {
							Toast('保存成功')
						},
						fail: (err) => {
							Toast('保存图片失败')
						},
					})
				},
				fail: (err) => {
					Toast('保存图片失败')
				},
			})
		} else {
			if (
				wx.getSystemInfoAsync({
					success: (result) => {
						if (result.platform === 'ios' && category !== 'receipt') {
							this.uploadUserImage(1)
						} else {
							let itemList = []
							if (category === 'receipt') {
								// if (result.platform === 'ios') {
								// 	itemList = ['回执（可自行打印，推荐）', ' 回执包邮寄（含纸质照片+回执）']
								// } else {
								// 	itemList = ['电子回执+电子照（推荐）', '纸质回执（含电子回执、包邮寄）']
                // }
                
                this.uploadUserImage(0)
							} else {
								itemList = ['电子照', '冲印照']
							}
							wx.showActionSheet({
								itemList: itemList,
								success: (result) => {
									this.uploadUserImage(result.tapIndex)
								},
							})
						}
					},
				})
			);
		}
	},

	// 上传处理后的图片,更新用户对应的图片信息
	async uploadUserImage(type = 0) {
		wx.getImageInfo({
			src: this.data.image + '',
			success: (res) => {
			},
			complete: async (res) => {
				console.log('==getImageInfo-complete', res)
				var watermarkImage = this.data.image
				if(res.path) {
					var watermarkImage = await uploadFile(res.path)
				}
				console.log('==watermarkImage', watermarkImage)
				try{
					let photoService = new PhotoService()
					photoService
						.updatePhoto(photoId, {
							// picId: '',
							picId: pic_id,
							watermarkImage,
							isChangeCloth: this.data.selectedCloth == 'none' ? false : true,
							clothKey: this.data.selectedCloth == 'none' ? null : this.data
								.selectedCloth,
							selectedColor: this.data.selectedColor,
						})
						.then((res) => {
							wx.navigateTo({
								url: `/pages/orderConfirm/orderConfirm?photoId=${res.data.id}&productId=${productId}&type=${type}&watermarkImage=${watermarkImage}&selectedCloth=${this.data.selectedCloth}&selectedColor=${this.data.selectedColor}&picId=${pic_id}`,
							})
						})
						.catch((res)=>{
							wx.navigateTo({
								url: `/pages/orderConfirm/orderConfirm?photoId=${pic_id}&productId=${productId}&type=${type}&watermarkImage=${watermarkImage}&selectedCloth=${this.data.selectedCloth}&selectedColor=${this.data.selectedColor}&picId=${pic_id}`,
							})
						})
				}catch(e){
					wx.navigateTo({
						url: `/pages/orderConfirm/orderConfirm?photoId=${pic_id}&productId=${productId}&type=${type}&watermarkImage=${watermarkImage}&selectedCloth=${this.data.selectedCloth}&selectedColor=${this.data.selectedColor}&picId=${pic_id}`,
					})
				}
				
			}
		})
	},

	submit() {
		wx.showLoading({
			title: '上传中',
		})
		wx.getImageInfo({
			src: this.data.image,
			success: async (res) => {
				const watermarkImage = await uploadFile(res.path)
				const photoService = new PhotoService()
				await photoService.updatePhoto(photoId, {
					watermarkImage,
					isChangeCloth: this.data.selectedCloth == 'none' ? false : true,
					clothKey: this.data.selectedCloth == 'none' ? null : this.data.selectedCloth,
					selectedColor: this.data.selectedColor,
				})
				const orderService = new OrderService()
				const response = await orderService.updateOrder({
					orderId: this.data.orderId,
					photoId: photoId
				})
				wx.hideLoading()
				if (response.statusCode === 200) {
					wx.reLaunch({
						url: '/pages/orderDetail/orderDetail?id=' + this.data.orderId
					})
				}
			},
			fail: async (res) => {
				wx.hideLoading()
			}
		})
	},
})